<template>
    <div>
        <div>
            <div class="searchTime" style="margin-bottom:15px;">
                <el-button type="primary" @click="dialogVisible = true" style="margin-right:20px;">{{shebeiType}}</el-button>
                <el-date-picker
                  v-model="bdate"
                  type="datetime"
                  value-format="timestamp"
                  placeholder="选择日期时间"
                  :picker-options="pickerOptionsStart"
                  style="margin-right: 10px;"
                ></el-date-picker>至
                <el-date-picker
                  v-model="edate"
                  type="datetime"
                  value-format="timestamp"
                  placeholder="选择日期时间"
                  :picker-options="pickerOptionsEnd"
                  style="margin-left: 10px;"
                ></el-date-picker>
                <el-button @click="searchCharts" type="primary" class="demonstration" style="margin-left:30px">搜索</el-button>
                <span style="float:right;"  v-if="this.loadingCharts == 2">
                    <span style="margin-right:10px">总条数：{{this.allPage}}</span>
                    <el-button type="primary" @click="search(0)">查看详细数据</el-button>
                    <el-button type="primary" @click="getcharts2(1)">导出详细数据</el-button>
                </span>
            </div>
            <div class="his_charts">
                <div class="hidden_charts" v-if="this.loadingCharts == 1">
                    <i class="el-icon-loading"></i>
                    正在加载
                </div>
                <div class="hidden_charts" v-if="this.loadingCharts == 3">
                    <div>
                        <div>
                            <i class="el-icon-loading"></i>
                            正在导出图文数据文件
                        </div>
                        <div class="hisPercent">
                            <el-progress :text-inside="true" :stroke-width="26" :percentage="this.schedule" color="#5981a5cc"></el-progress>
                        </div>
                    </div>
                    
                </div>
                <div :style="this.loadingCharts == 2 ? 'opacity: 1':'opacity: 0'">
                    <div class="his_charts_dao"  >
                        <p v-if="this.loadingCharts == 2">{{ this.name }}时间范围曲线图展示</p>
                    </div>
                    <div class="his_charts_none" v-if="this.allPage == 0">
                        未查询到当前设备历史数据
                    </div>
                    <div class="chart_detail"  id="myChart"  ref="chart"  />
                    <p class="his_charts_ts"  v-if="this.loadingCharts == 2">*y轴范围取自该段历史记录数值的最大最小值，鼠标可滑动拖动展示y轴范围</p>
                    <div class="his_charts_but"  v-if="this.loadingCharts == 2 && this.allPage > 0">
                        <el-button type="primary" class="his_dao" @click="getcharts2(0)" v-if="this.isMobile !== 'mobile'">导出曲线图文</el-button>
                    </div>
                </div>
                
           
                
            </div>
        </div>
        <el-dialog
            title="详细数据"
            :visible.sync="dialogTable"
            width="60%"
            :append-to-body="true"
            :before-close="tableClose">
            <div>
                <el-table
                    :data="tableData"
                    height="700px"
                    style="width: 100%">
                <el-table-column
                    type="index"
                    label="序列号"
                    width="100px">
                    <template>
                    </template>   
                </el-table-column>
                <el-table-column
                    prop="name"
                    label="设备名称"
                    width="">
                </el-table-column>
                <el-table-column
                    prop="time"
                    label="时间">
                </el-table-column>
                <el-table-column
                    prop="value"
                    label="数据/类型">
                </el-table-column>
                </el-table>

                <div class="page_wrap">
                    <el-pagination
                    background
                    layout="prev, pager, next"
                    @current-change="handleCurrentChange"
                    :page-size= "pageSize"
                    :total="allPage">
                    </el-pagination>
                </div>
            </div>
        </el-dialog>
        <el-dialog
            title="设备绑定"
            :visible.sync="dialogVisible"
            width="60%"
            :append-to-body="true"
            :before-close="handleClose">
            <div style="color:#fff;">
                <div class="shebeiBox">
                    <h3>选择类型</h3>
                    <div class="warnhis_type_flex" >
                        <div class="warnhis_type_but" v-for="(item,index) in this.sidemenu" :key="index" @click="selectType(item)">
                            <div :class="item.active == 1 ? 'warnhis_type_active':'warnhis_type_nomal'">
                                {{item.typename}}
                            </div>
                        </div>
                    </div>
                </div>
                <div class="shebeiBox" style="margin-top:30px;">
                    <h3 >选择设备</h3>
                    <div class="warnhis_type_flex">
                        <div class="warnhis_type_but" v-for="(item,index) in this.childData" :key="index" @click="selectTypelink(item)">
                            <div :class="item.active == 1 ? 'warnhis_type_active':'warnhis_type_nomal'">
                                {{item.name}}
                            </div>
                        </div>
                    </div>
                </div>
                <div class="shebeiBox shebeiBox3" style="margin-top:30px;">
                    <h3 >选择设备子项</h3>
                    <div class="warnhis_shebei">
                        <div class="warnhis_type_flex">
                            <div class="warnhis_type_but" v-for="(item,index) in this.leafChildData.unit" :key="index" @click="selectTypedata(item)">
                                <div class="warnhis_type_nomal">
                                    {{item.name}}
                                </div>
                            </div>
                        </div>
                    </div>
                    
                </div>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import $ from 'jquery';
import allDataJson from "../../../static/allDataJson.json"; //总数据模板
import * as echarts from 'echarts'
import PizZip from 'pizzip'
import docxtemplater from 'docxtemplater'
import JSZipUtils from 'jszip-utils'
import { saveAs } from 'file-saver'
export default {
    data () {
        return{
            tableData:[],
            nowPage:0,
            allPage:0,
            pageSize:100,//详细数据展示每页条数
            pageSizeD:5000,//表格导出每条接口请求数量
            isMobile: '',
            shebeiType:'选择查询设备',
            radio1: '1',
            radio2:'',
            radio3:'',
            dialogVisible: false,
            dialogTable:false,
            loadingCharts:0,//等待展示切换
            chart0: null,
            echartsCurver:{},
            bdate: '',
            edate: this.getCurrentTimestampInSeconds(),
            starttime: '',//真实回传开始时间
            endtime: '',//真实回传结束时间
            serial:'',
            name:'',
            backName:'',
            echartsData:[],//曲线数据
            schedule:0,//导出图文进度
            pickerOptionsStart: {
                disabledDate: time => {
                let endDateVal = this.edate;
                if (endDateVal) {
                    return time.getTime() > new Date(endDateVal).getTime();
                }
                }
            },
            pickerOptionsEnd: {
                disabledDate: time => {
                let beginDateVal = this.bdate;
                if (beginDateVal) {
                    return time.getTime() < new Date(beginDateVal).getTime();
                }
                }
            },
            sidemenu : [],
            childData: [],
            leafChildData:{},
            nowselect:{},
            nowLeafSerial: '',
            //图片
            img1: '',
            form:{
                type:'',
                backName:'',
                name:'',
                bTime:'',
                eTime:'',
            },
            min:0,
            max:0,
        }
    },
    created() {
        this.isMobile = localStorage.getItem("当前终端")
        this.getlist()
    },
    methods: {
        getCurrentTimestampInSeconds() {
            const now = new Date();
            const year = now.getFullYear();
            const month = now.getMonth() + 1; // 注意月份是从0开始的
            const day = now.getDate();
            const hours = now.getHours();
            const minutes = now.getMinutes();
            const seconds = now.getSeconds();

            return new Date(year, month - 1, day, hours, minutes, seconds).getTime();
        },
        // 获取设备列表
        getlist(){
            var params = {
                "getdevlink":"",
                [localStorage.getItem("cookieName")]:localStorage.getItem("_token")
            }
            this.$http.post(this.$baseUrl, params).then((res) => {
                this.sidemenu = []
                if(res.data.result == 'ok'){
                    var data = res.data.getdevlink
                    for(var i = 0; i < data.length; i++){
                        var s = 0
                        if(data[i].type != 31 && data[i].type != 32){//屏蔽掉31 32无线网关模块设备
                            for(var y = 0; y < data[i].devlink.length; y++){
                                if(data[i].devlink[y].ready == 1){
                                    s++
                                }
                            }
                            if(s > 0){
                                var arr = {
                                    devlink:data[i].devlink,
                                    type:data[i].type,
                                    typename:data[i].typename,
                                    active:0
                                }
                                this.sidemenu.push(arr)
                            }
                        }  
                    }
                }
            })
        },
        // 点击设备类型
        selectType(data){
            for(var a = 0;  a < this.sidemenu.length; a++){
                if(this.sidemenu[a].type == data.type){
                    this.sidemenu[a].active = 1
                }else{
                    this.sidemenu[a].active = 0
                }
            }
            this.childData = []
            this.leafChildData = {}
            for(var i = 0; i < data.devlink.length; i++){
                if(data.devlink[i].ready == 1){
                    var arr = {
                        type:data.type,
                        addr:data.devlink[i].addr,
                        uid:data.devlink[i].uid,
                        typename:data.typename,
                        name:data.devlink[i].name,
                        active:0
                    }
                    this.childData.push(arr)
                }
            }
        },
        // 点击具体设备
        selectTypelink(data){
            for(var a = 0;  a < this.childData.length; a++){
                if(this.childData[a].uid == data.uid && this.childData[a].addr == data.addr && this.childData[a].type == data.type){
                    this.childData[a].active = 1
                }else{
                    this.childData[a].active = 0
                }
            }
            this.leafChildData = {}
            var params = {
                "getdevinfo":[{
                    "uid":data.uid,
                    "type":data.type,
                    "addr":data.addr,
                    "unittype":"id-name-ready-recordtime"
                }],
                [localStorage.getItem("cookieName")]:localStorage.getItem("_token")
            }
            this.$http.post(this.$baseUrl, params).then((res) => {
                if(res.data.result == 'ok'){
                    var srt = []
                    for(var i = 0; i < res.data.getdevinfo[0].unit.length; i++){
                        if(res.data.getdevinfo[0].unit[i].ready == 1 && res.data.getdevinfo[0].unit[i].recordtime != 0){
                            srt.push(res.data.getdevinfo[0].unit[i])
                        }
                    }
                    var arr = {
                        type:data.type,
                        addr:data.addr,
                        uid:data.uid,
                        typename:data.typename,
                        name:data.name,
                        unit:srt
                    }
                    this.leafChildData = arr
                }
            })
        },
        // 点击具体设备子项
        selectTypedata(data){
            this.nowselect = {
                type:this.leafChildData.type,
                addr:this.leafChildData.addr,
                uid:this.leafChildData.uid,
                id:data.id,
                name:data.name,
            }
            this.shebeiType = this.leafChildData.typename+'-'+this.leafChildData.name+'-'+data.name
            this.form.type = this.leafChildData.typename
            this.form.backName = this.leafChildData.name
            this.form.name = data.name
            this.dialogVisible = false
            var params = {
                "getdevinfo":[
                    {
                    "uid": this.leafChildData.uid,
                    "type": this.leafChildData.type,
                    "addr": this.leafChildData.addr,
                    "unittype":"id-min-max"
                    }
                ],
                [localStorage.getItem("cookieName")]:localStorage.getItem("_token")
            }
            this.$http.post(this.$baseUrl, params).then((res) => {
                if(res.data.result == 'ok'){
                    this.loadingCharts = 0//清屏 隐藏刚刚查询的内容
                    var data2 = res.data.getdevinfo[0].unit
                    for(var i = 0; i < data2.length; i++){
                        if(data.id == data2[i].id){
                            this.min = data2[i].min
                            this.max = data2[i].max
                        }
                    }
                }else{
                    this.$notify({
                        title: '曲线范围获取失败',
                        type: 'warning',
                        duration: 1500
                    });
                }
            })
        },
        // 关闭选择设备框
        handleClose(){
            this.dialogVisible = false
            if(this.shebeiType == '选择查询设备'){
                this.nowselect = {}
                // 清除选中设备状态
                for(var a = 0;  a < this.sidemenu.length; a++){
                    this.sidemenu[a].active = 0
                }
                // 清除子设备展示
                this.childData = []
                this.leafChildData = {}
            }
        },
        // 搜索
        search(val) {
            this.tableData = []
            this.dialogTable = true
            var pages = this.nowPage //分页请求
            if(this.afterEtime == ''){
                this.$notify({
                    title: '请选择结束时间',
                    type: 'warning',
                    duration: 1500
                });
                return false
            }else{
                if(this.afterBetime == ''){
                    this.afterBetime = 0
                }
                if(this.afterEtime == 0){
                    this.edate = Number((Date.now().toString().slice(0, 10)).toString()+'000')
                }
                this.form.bTime = this.formatDate(this.afterBetime * 1000, 'YYYY-MM-DD H:m:s')
                this.form.eTime = this.formatDate(this.afterEtime * 1000, 'YYYY-MM-DD H:m:s')
                var params = {
                    "getdevhistory":{
                        "btime":this.afterBetime,
                        "etime":this.afterEtime,
                        "size":this.pageSize,
                        "page":pages,
                        "uid":this.nowselect.uid,
                        "type":this.nowselect.type,
                        "addr":this.nowselect.addr,
                        "id":this.nowselect.id
                    },
                    [localStorage.getItem("cookieName")]:localStorage.getItem("_token")
                };
                this.$http.post(this.$baseUrl,params).then((res)=>{
                    console.log(res.data)
                    if(res.data.result == 'command type error.'){
                        this.$notify({
                            title: '请选择设备',
                            type: 'warning',
                            duration: 1500
                        });
                        return false;
                    }else if(res.data.result == 'ok'){
                        for(var i = 0; i <res.data.getdevhistory.length;i++){
                            res.data.getdevhistory[i].value = res.data.getdevhistory[i].value.toFixed(2)
                            res.data.getdevhistory[i].time = this.formatDate(res.data.getdevhistory[i].time * 1000, 'YYYY-MM-DD H:m:s'); 
                            res.data.getdevhistory[i].name = this.nowselect.name
                        }
                        this.tableData = res.data.getdevhistory;
                        this.allPage =  res.data.count;
                    }
                    
                })
            }
        },
        tableClose(){
            this.dialogTable = false
        },
        //曲线接口请求
        searchCharts(){
            if(this.afterBetime == ''){
                this.afterBetime = 0
            }
            if(this.afterEtime == ''){
                this.$notify({
                    title: '请选择结束时间',
                    type: 'warning',
                    duration: 1500
                });
                return false
            }
            this.nowPage = 0
            if(this.afterEtime == 0){
                this.edate = Number((Date.now().toString().slice(0, 10)).toString()+'000')
            }
            
            this.loadingCharts = 1 //加载动画
            this.echartsCurver = {
                'value':[],
                'time':[],
            }
            var params = {
                "getdevhistorymap":{
                    "btime":this.afterBetime,
                    "etime":this.afterEtime,
                    "uid":this.nowselect.uid,
                    "addr":this.nowselect.addr,
                    "id":this.nowselect.id
                },
                [localStorage.getItem("cookieName")]:localStorage.getItem("_token")
            };
            this.$http.post(this.$baseUrl,params).then((res)=>{
                if(res.data.result == 'command type error.'){
                    this.$notify({
                        title: '请选择设备',
                        type: 'warning',
                        duration: 1500
                    });
                    this.loadingCharts = 0 //取消加载动画
                    return false;
                }else if(res.data.result == 'ok'){
                    this.starttime = res.data.starttime
                    this.endtime = res.data.endtime
                    this.form.bTime = this.formatDate(this.starttime * 1000, 'YYYY-MM-DD H:m:s')
                    this.form.eTime = this.formatDate(this.endtime * 1000, 'YYYY-MM-DD H:m:s')
                    this.name = this.form.name
                    this.backName = this.form.backName
                    this.allPage = res.data.count
                    if(this.allPage == 0){
                        this.loadingCharts = 2  //展示曲线
                    }else{
                        var l = res.data.getdevhistorymap.length
                        for(var i = 0; i < l; i++){
                            this.echartsCurver['value'].push(res.data.getdevhistorymap[i].v) 
                            if(i == l-1){
                                this.echartsCurver['time'].push(this.formatDate(this.endtime * 1000, 'YYYY-MM-DD H:m:s'))
                                // this.echartsCurver['time'].push(this.afterEtime)
                                setTimeout(()=> {
                                    this.loadingCharts = 2  //展示曲线
                                    this.initChart()
                                },3000)
                                this.initChart()
                            }else if(i == 0){
                                this.echartsCurver['time'].push(this.formatDate(this.starttime * 1000, 'YYYY-MM-DD H:m:s'))
                            }else{
                                this.echartsCurver['time'].push(this.formatDate(this.starttime+i * 1000, 'YYYY-MM-DD H:m:s'))
                            }
                        }
                    }
                }
                
                
            })
        },
        // 折线图
        initChart() {
            this.chart = echarts.init(this.$refs.chart);
            // 绘制图表，this.echarts1_option是数据
            var option = {
                tooltip: {
                    trigger: 'axis',
                    formatter: '{a0}: {c0}'
                },
                animation:false,
                legend: {
                    show:false,
                    data: [this.name]
                },
                grid: {
                    //统计图距离边缘的距离
                    top: "8%",
                    left: "6%",
                    right: "6%",
                    bottom: "10%"
                },
                // dataZoom: [
                //         {
                //             show: false,//dataZoom，框选区域缩放，自动与存在的dataZoom控件同步，分别是启用，缩放后退
                //             start: 0,
                //             end: 100
                //         }
                // ],	
                
                xAxis: [
                    {
                    //x轴
                    // show:false,
                    type: "category", //数据类型为不连续数据
                    boundaryGap: false, //坐标轴两边是否留白
                    axisLine: {
                        //坐标轴轴线相关设置。数学上的x轴
                        show: true,
                        lineStyle: {
                        color: "#233e64" //x轴颜色
                        },
                        //boundaryGap: true
                    },
                    axisLabel: {
                        //坐标轴刻度标签的相关设置
                        textStyle: {
                        color: "#6a9cd5"
                        },
                        interval:this.echartsCurver['time'].length,//x轴坐标间距，分20格
                        // interval:2,//x轴坐标间距，分20格
                        // rotate : 45,  // 标签倾斜的角度
                        showMaxLabel: true,//关键部分，显示最后一个label
                    },
                    // axisTick: { show: true }, //刻度点数轴
                    data: this.echartsCurver['time']
                    }
                ],
                yAxis: [
                    {
                    //y轴的相关设置
                    type: "value", //y轴数据类型为连续的数据
                    // min:"dataMin",//y轴上的刻度最小值
                    // max:"dataMax",//y轴上的刻度最大值
                    min:this.min,//y轴上的刻度最小值
                    max:this.max,//y轴上的刻度最大值

                    splitNumber: 10, //y轴上的刻度段数
                    splitLine: {
                        //y轴上的y轴线条相关设置
                        show: true,
                        lineStyle: {
                        color: "#233e64"
                        },
                    },
                    axisLine: {
                        //y轴的相关设置
                        show: true,
                        lineStyle: {
                        color: "#233e64" //y轴颜色
                        }
                    },
                    axisLabel: {
                        //y轴的标签相关设置
                        textStyle: {
                        color: "#6a9cd5"
                        }
                    },
                    axisTick: { show: true }, //刻度点数轴
                    boundaryGap: [0.2, 0.2]

                    }
                ],
                dataZoom: [
                    {
                        type: 'inside', //无滑动条内置缩放   
                        // type: 'slider', //缩放滑动条
                        show: true, //开启
                        yAxisIndex: [0], //Y轴滑动
                        //  xAxisIndex: [0],//X轴滑动
                        start: 0, //初始化时，滑动条宽度开始标度 百分比
                        end: 100, //初始化时，滑动条宽度结束标度 百分比
                        // startValue: 0,
                        // endValue: 30,
                        fillerColor: 'rgba(61,234,255,0.2)', //滑块的颜色
                        // backgroundColor: 'transparent',  // 滑块轨道的颜色
                        borderColor: 'rgba(61,234,255,0.2)', // 滑块轨道边框的颜色
                        width: 20,   // 滑块高度
                        handleStyle:{ /*手柄的样式*/ 
                            color:"rgba(61,234,255,0.2)", 
                            borderColor:"rgba(61,234,255,0.6)"
                        },
                        textStyle: {
                            color: "#fff" //滚动条两边字体样式
                        }
                    }
                ],
                series: [
                    {
                    name: this.name,
                    type: "line", //统计图类型为折线图
                    smooth: true, //是否平滑曲线显示
                    symbolSize: 0, //数据点的大小，[0,0]//b表示宽度和高度
                    lineStyle: {
                        //线条的相关设置
                        normal: {
                        color: "#3deaff" // 线条颜色
                        }
                    },
                    areaStyle: {
                        //区域填充样式
                        normal: {
                        //线性渐变，前4个参数分别是x0,y0,x2,y2(范围0~1);相当于图形包围盒中的百分比。如果最后一个参数是‘true’，则该四个值是绝对像素位置。
                        color: new echarts.graphic.LinearGradient(
                            0,
                            0,
                            0,
                            1,
                            [
                                { offset: 0, color: "rgba(61,234,255, 0.9)" },
                                { offset: 0.7, color: "rgba(61,234,255, 0)" }
                            ],
                            false
                        ),

                        shadowColor: "rgba(53,142,215, 0.9)", //阴影颜色
                        shadowBlur: 20 //shadowBlur设图形阴影的模糊大小。配合shadowColor,shadowOffsetX/Y, 设置图形的阴影效果。
                        }
                    },
                    data:this.echartsCurver['value'] 
                    },
                ]
            }
            this.chart.setOption(option);
            // ECHARTS图表的图片并转为base64格式
            // this.img1 = this.chart.getDataURL({
            // pixelRatio: 2,      // 导出的图片分辨率比例，默认为 1。
            // backgroundColor: '#fff'   // 导出的图片背景色，默认使用 option 里的 backgroundColor
            // });
        },
        // 获取全部详细数据
        getcharts2(val){
            if(val == 0){//导出曲线图文
                this.schedule = 30
                this.loadingCharts = 3
                setTimeout(() => {
                    this.schedule = 60
                },1000)
                setTimeout(() => {
                    this.schedule = 99
                },2000)
                setTimeout(() => {
                    this.loadingCharts = 2
                    this.wirterWord()
                },3000)
            }else{//导出数据表格
                if(this.allPage > 10000 || window.location.hostname == '127.0.0.1'){
                    var params = {
                        "backupdevhistory":{
                            "btime":this.afterBetime,
                            "etime":this.afterEtime,
                            "uid":this.nowselect.uid,
                            "id":this.nowselect.id
                        },
                        [localStorage.getItem("cookieName")]:localStorage.getItem("_token")
                    };
                    this.$http.post(this.$baseUrl,params).then((res)=>{
                        if(res.data.result == 'ok'){
                            if(window.location.hostname == '127.0.0.1'){//在区域控制器中
                                this.$notify({
                                    title: '正在后台自动导出中……',
                                    type: 'success',
                                    duration: 1500
                                });
                            }else{
                                this.$notify({
                                    title: '正在后台自动导出中，请到区域控制器设备中等待查看……',
                                    type: 'success',
                                    duration: 2500
                                });
                            }
                        }else{
                            this.$message({
                                message: '导出失败',
                                type: 'warning',
                                duration: 1500
                            });
                        }
                    })
                }else{
                    this.schedule = 0
                    setTimeout(() => {
                        this.getcharts()
                    },1000)
                }
            }
            
            
        },
        // excel表格数据导出
        getcharts: async function () {
            this.loadingCharts = 3
            var pageNum = Math.ceil(this.allPage/this.pageSizeD) 
            var copies = 100 / pageNum //判断进度条每次接口走完＋多少进度
            if(copies >= 0 ){
                copies = Number(copies.toFixed(0))
            }else{
                copies = Number(copies.toFixed(1))
            }
            console.log(copies)
            this.echartsData = []
            var num = 0
            for(var i = 0; i < pageNum; i++){
                var params = {
                    "getdevhistory":{
                        "btime":this.afterBetime,
                        "etime":this.afterEtime,
                        "size":this.pageSizeD,
                        "page":i,
                        "uid":this.nowselect.uid,
                        "type":this.nowselect.type,
                        "addr":this.nowselect.addr,
                        "id":this.nowselect.id
                    },
                    [localStorage.getItem("cookieName")]:localStorage.getItem("_token")
                };
                await this.$http.post(this.$baseUrl,params).then((res)=>{
                    if(res.data.result == "ok"){
                        if(i == pageNum-1){ //最后一条走完不要显示100%，留出等待表格生成的时间
                            var ss = this.schedule + copies
                            if(ss >= 100 ){
                                this.schedule = 99
                            }else{
                                this.schedule = ss
                            }
                        }else{
                            this.schedule = this.schedule + copies
                        }
                        console.log(this.schedule)
                        var arr = res.data.getdevhistory
                        for(var y = 0; y < arr.length; y++){
                            num+=1
                            var srr = {
                                backName:this.backName,
                                name:this.name,
                                time : this.formatDate(arr[y].time * 1000, 'YYYY-MM-DD H:m:s'),
                                value : arr[y].value.toFixed(2),
                                number : num
                            }
                            this.echartsData.push(srr)
                            // 判断到最后一条
                            if(i == pageNum-1 && y == arr.length-1 ){
                                setTimeout(() => {
                                    this.loadingCharts = 2
                                },3000)
                            }
                        }
                    }
                }).catch(error => {
                    console.log(error);
                });
                
            }
            require.ensure([], () => {
                const { export_json_to_excel } = require('../../vendor/Export2Excel');
                const tHeader = ['编号','设备名称','名称','值','时间'];
                const filterVal = ['number','backName','name','value','time'];
                const list = this.echartsData;
                const data = this.formatJson(filterVal, list);
                export_json_to_excel(tHeader, data, '历史数据导出表格');
            })
        },
        formatJson(filterVal, jsonData) {
            return jsonData.map(v => filterVal.map(j => v[j]))
        },
        // 导出曲线生成的图片
        getFullCanvasDataURL(){
            //将第一个画布作为基准。
                var baseCanvas = $("#myChart").find("canvas").first()[0];
                if(!baseCanvas){
                    return false;
                };
                var width = baseCanvas.width;
                var height = baseCanvas.height;
                // var width = 570;
                // var height = 200;
                var ctx = baseCanvas.getContext("2d");
                //遍历，将后续的画布添加到在第一个上
                $("#myChart").find("canvas").each(function(i,canvasObj){
                    if(i>0){
                        var canvasTmp = $(canvasObj)[0];
                        ctx.drawImage(canvasTmp,0,0,width,height);
                    }
                });
                //获取base64位的url
                return baseCanvas.toDataURL();
        },
        // 导出echarts图片，格式转换，官方自带，不需要修改
        base64DataURLToArrayBuffer(dataURL) {
            const base64Regex = /^data:image\/(png|jpg|svg|svg\+xml);base64,/;
            if (!base64Regex.test(dataURL)) {
                return false;
            }
            const stringBase64 = dataURL.replace(base64Regex, "");
            let binaryString;
            if (typeof window !== "undefined") {
                binaryString = window.atob(stringBase64);
            } else {
                binaryString = new Buffer(stringBase64, "base64").toString("binary");
            }
            const len = binaryString.length;
            const bytes = new Uint8Array(len);
            for (let i = 0; i < len; i++) {
                const ascii = binaryString.charCodeAt(i);
                bytes[i] = ascii;
            }
            return bytes.buffer;
        },
        //导出word
        wirterWord() {
            this.img1 = this.getFullCanvasDataURL()
            //这里要引入处理图片的插件，下载docxtemplater后，引入的就在其中了
            var ImageModule = require('docxtemplater-image-module-free');
            var fs = require("fs");
            const expressions = require("angular-expressions");
            let _this = this;
            // 读取并获得模板文件的二进制内容，放在项目中即可
            JSZipUtils.getBinaryContent("../../../static/demo.docx", function(error, content) {
                if (error) {
                throw error;
                };

                expressions.filters.size = function (input, width, height) {
                return {
                    data: input,
                    size: [width, height],
                };
                };
                function angularParser(tag) {
                const expr = expressions.compile(tag.replace(/’/g, "'"));
                return {
                    get(scope) {
                    return expr(scope);
                    },
                };
                }

                // 图片处理
                let opts = {}
                opts = { centered: false };
                opts.getImage = (chartId)=> {
                return _this.base64DataURLToArrayBuffer(chartId);
                }
                opts.getSize = function(img, tagValue, tagName) {
                //自定义指定图像大小，此处可动态调试各别图片的大小
                // if (tagName === "img1") return [400,250];
                return [570,200];
                }

                // 创建一个PizZip实例，内容为模板的内容
                let zip = new PizZip(content);
                // 创建并加载docxtemplater实例对象
                let doc = new docxtemplater();
                doc.attachModule(new ImageModule(opts));
                doc.loadZip(zip);
                
                // 设置模板变量的值
                doc.setData({
                ..._this.form,
                table: _this.echartsData,
                img1: _this.img1,
                });

                try {
                // 用模板变量的值替换所有模板变量
                doc.render();
                } catch (error) {
                // 抛出异常
                let e = {
                    message: error.message,
                    name: error.name,
                    stack: error.stack,
                    properties: error.properties
                };
                console.log(JSON.stringify({ error: e }));
                throw error;
                }

                // 生成一个代表docxtemplater对象的zip文件（不是一个真实的文件，而是在内存中的表示）
                let out = doc.getZip().generate({
                type: "blob",
                mimeType:
                    "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
                });
                // 将目标文件对象保存为目标类型的文件，并命名
                saveAs(out, "历史曲线记录图文导出表.docx");
            });
        },

        // 分页请求
        handleCurrentChange(page){
            this.$store.commit("changLoading", true);
            this.nowPage = page - 1;
            this.search(1);
        },
    },
    computed:{
          afterBetime() {
            return this.bdate === 0 ? 0 : this.bdate / 1000;
            },
        afterEtime() {
            return this.edate === 0 ? 0 : this.edate / 1000;
        }
    }
}
</script>

<style scoped>
    .el-card {
    background: none;
    color: #fff;
    border: 1px solid rgba(89, 129, 165, 0.4);
    }
    /deep/ .el-card__header {
    background: rgba(89, 129, 165, 0.2);

    border-bottom: none;
    }
    .box-card {
    /* overflow: hidden; */
    }
    .card_padding_chart{
    padding: 7px 0;
    }
    /deep/ .el-input__inner{
        background: rgba(255, 255, 255, 0);
        border: 1px solid rgba(255, 255, 255, 0.3);
        width: 100%;
        color: #fff;
    }
    /deep/ .el-form-item__label{
        color: #fff;
    }

.shebeiDetails .el-input{
    width: 200px;
}
/deep/ .shebeiDetails .el-form-item__label{
    width: 80px;
    color: #fff;
}
/deep/ .el-dialog__title{
    color: #fff;
}
/* /deep/ .el-dialog__headerbtn .el-dialog__close{
    color: #fff;
} */
/deep/ .el-radio.is-bordered{
    color: #fff;
    margin: 10px;
    width: 140px;
}
/deep/ .el-radio{
    color: #fff;
}
    /deep/ .el-table--enable-row-hover .el-table__body tr:hover>td{
        background: #4e6888;
    }
    /deep/ .el-table--striped .el-table__body tr.el-table__row--striped td {
        background: #4e6888;
    }
    /deep/ .el-table--border{
        border: none;
    }
    /deep/ .el-table th, /deep/  .el-table tr{
        background-color: transparent !important;
        color: #fff;
    }
    /deep/ .el-table, .el-table__expanded-cell{
        background-color: transparent !important;
    }
    /deep/ .el-table__header-wrapper{
        /* background-color: #5f7998 !important; */
        background-color: #5981a533 !important;
        border: 1px solid #475c6f;
        border-bottom: none;
    }
    /deep/ .is-scrolling-none{
        /* background: #4e6888 !important; */
            background: rgba(89,129,165,.4) !important;
    }
    /deep/ .el-table td, .el-table th.is-leaf{
        border-bottom: 1px solid #ebeef542;
        background-color: transparent !important;
    }
     /* 清除底部横线 */
    .el-table::before {
        height: 0px;
    }
    .el-table--border::after{
        display: none;
    }
    /deep/  .el-button {
    background: rgba(89, 129, 165, 0.8);
    border: none;
}
.el-pagination{
    margin-top: 20px;
    text-align: right;
}
/deep/ .el-table th.is-leaf{
    border-bottom:none !important;
}
/* 曲线 */
.his_charts{
    height: 700px;
    width: 100%;
    position: relative;
    overflow: hidden;
}
.hidden_charts{
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #fff;
    background: rgba(0, 0, 0, 0.2);
    font-size: 18px;
}
.hidden_charts div{
    text-align: center;
}
.hisPercent{
    width: 800px;
    margin-top: 20px;
}
/deep/ .el-progress-bar__outer{
    background-color: #ebeef52e;
}
.chart_detail {
    height: 330px;
    position: relative;
}
.his_charts_dao{
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: center;
}
.his_dao{
    float: right;
    margin-right: 20px;
}
.his_charts_dao{
    font-size: 24px;
    color: #fff;
}
.his_charts_none{
    text-align: center;
    position: relative;
    top: 80px;
    font-size: 22px;
    color: #e6a23c;
}
.his_charts_ts{
    color:#e6a23c;
    padding-left: 20px;
    font-size: 16px;
}
/deep/ .his_charts_but .el-button {
    background: rgba(89, 129, 165, 0.8);
    border: 1px solid #8f9ba6;
}
.his_charts_but{
    height: 30px;
    width: 100%;
    margin-top: 10px;
}
.warnhis_type_flex{
    width: 100%;
    display: flex;
    flex-wrap: wrap;
}
.warnhis_type_but{
    margin-right: 20px;
    margin-top: 20px;
    border: 1px solid #ffffff8a;
    border-radius: 5px;
    cursor: pointer;
}
.warnhis_type_nomal{
    height: 50px;
    line-height: 50px;
    padding: 0px 15px;
    background: #36363614;
}
.warnhis_type_active{
    height: 50px;
    line-height: 50px;
    padding: 0px 15px;
    background: #b8e2ff29;
}
.warnhis_shebei{
    width: 100%;
    height: 300px;
    color: #fff;
    overflow-y: scroll;
}
</style>

